<template>
  <div>
    <Card :bordered="false" dis-hover class="ivu-mt pt10">
      <Form ref="formValidate" :model="formValidate" :label-width="labelWidth" :label-position="labelPosition">
        <Row type="flex" :gutter="24">
          <Col>
            <FormItem :label="$t('page.stock.outbound_order_no')+'：'" label-for="store_name">
              <Input enter-button style="width:300px"  :placeholder="$t('page.stock.pleace_search_freright')" v-model="formValidate.store_name" />
            </FormItem>
          </Col>
          <Col>
            <FormItem :label="$t('page.stock.archiving_status')+'：'" >
              <Select
                  v-model="formValidate.archiving_status"
                  clearable
                  style="width:200px;"
              >
                <Option :value="0">{{ $t('page.stock.not_archiving') }}</Option>
                <Option :value="1">{{ $t('page.stock.waiting_settlement') }}</Option>
                <Option :value="2">{{ $t('page.stock.already_settlement') }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col>
            <FormItem :label="$t('page.stock.archiving_period')+'：'">
              <DatePicker
                  type="month"
                  :placeholder="$t('page.stock.select_date')"
                  @on-change="onchangeTime"
                  style="width: 260px;">
              </DatePicker>
            </FormItem>
          </Col>
          <Col>
            <FormItem :label="$t('page.stock.warehouse')+'：'">
              <Select
                  v-model="formValidate.warehouse_name"
                  clearable
                  style="width:200px;"
              >
                <Option
                    v-for="item in stockNameList"
                    :value="item.value"
                    :key="item.value"
                >{{ item.label }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col>
            <div class="search" @click="search">{{$t('page.stock.search')}}</div>
          </Col>
          <Col>
            <div class="reset" @click="reset">{{$t('page.stock.reset')}}</div>
          </Col>
		    </Row>
      </Form>
    </Card>
    <Card :bordered="false" dis-hover class="mt15 tablebox">
      <div class="freight_tabs tabbox">
        <Tabs v-model="formValidate.type" @on-click="onClickTab">
          <!-- <TabPane v-for="(item, index) in headerList" :key="index" :label="item.name + '(' + item.count + ')'"
                   :name="item.type.toString()" /> -->
				   <TabPane v-for="tab in tabList" :key="tab.type" :label="tab.name + '(' + tab.count + ')'"
				            :name="tab.type.toString()" />
        </Tabs>
      </div>
      <div class="table mt20">
<!--        <router-link :to="roterPre+'/stock/freight_edit'">-->
<!--          <Button type="primary" class="bnt">添加出库单</Button-->
<!--          ></router-link>-->
        <vxe-table
            border="inner"
            ref="xTable"
            height="600"
            class="mt25"
            :loading="loading"
            row-id="id"
            :checkbox-config="{reserve: true}"
            @checkbox-all="checkboxAll"
            @checkbox-change="checkboxItem"
            :data="freightList">
          <template #empty>
            <p class="empty-text">{{$t('page.product.no_data')}}</p>
          </template>
          <vxe-column field="out_bounding_biz_no" :title="$t('page.stock.outbound_order_no')" width="150"></vxe-column>
          <vxe-column field="warehouse_id" :title="$t('page.stock.stock_name')" min-width="120" align="left" fixed="left">
            <template v-slot="{ row }">
              <div slot="content">
                <span v-if="row.warehouse_id == '1791498718751334401'">CA 5005</span>
                <span v-if="row.warehouse_id == '101816795504'">Houston</span>
              </div>
            </template>
          </vxe-column>
          <vxe-column field="tracking_number" :title="$t('page.stock.mater_tracking_no')" min-width="150"></vxe-column>
          <vxe-column field="order_nos" :title="$t('page.stock.po')" min-width="250"></vxe-column>
          <vxe-column field="delivery_method" :title="$t('page.stock.arrival_type')" min-width="200">
            <template v-slot="{ row }">
              <p v-if="row.delivery_method ='3'">{{$t('page.stock.warehouse_freight_service')}}</p>
            </template>
          </vxe-column>
          <vxe-column field="delivery_type" :title="$t('page.stock.delivery_method')" min-width="150">
            <template v-slot="{ row }">
              <p v-if="row.delivery_type ='1'">{{$t('page.stock.pick_up')}}</p>
            </template>
          </vxe-column>
          <vxe-column field="updated_at" :title="$t('page.stock.submit_time')" min-width="150">
            <template v-slot="{ row }">
              <span>{{ formatTimeNative(row.updated_at) }}</span> <!-- 调用格式化方法 -->
            </template>
          </vxe-column>
          <vxe-column field="status" :title="$t('page.stock.status')" min-width="90" align="center" fixed="right">
            <template v-slot="{ row }">
              <span v-if="row.status == 1">{{$t('page.stock.draft')}}</span>
              <span v-else-if="row.status == 3">{{$t('page.stock.submitted')}}</span>
              <span v-else-if="row.status == 4">{{$t('page.stock.to_ship')}}</span>
              <span v-else-if="row.status == 6">{{$t('page.stock.shipped')}}</span>
              <span v-else-if="row.status == 7">{{$t('page.stock.cancelled')}}</span>
              <span v-else-if="row.status == 9">{{$t('page.stock.completed')}}</span>
            </template>
          </vxe-column>
          <vxe-column field="archiving_status" :title="$t('page.stock.archiving_status')" min-width="90" align="center" fixed="right">
            <template v-slot="{ row }">
              <span v-if="row.archiving_status == 0">{{$t('page.stock.not_archiving')}}</span>
              <span v-else-if="row.archiving_status == 1">{{$t('page.stock.waiting_settlement')}}</span>
              <span v-else-if="row.archiving_status == 2">{{$t('page.stock.already_settlement')}}</span>
            </template>
          </vxe-column>

          <vxe-column field="archiving_period" :title="$t('page.stock.archiving_period')" min-width="100" fixed="right"></vxe-column>

          <vxe-column field="action" :title="$t('page.product.operate')" align="center" width="150" fixed="right">
            <template #default="{ row, rowIndex }">
              <a @click="detail(row.id)">{{$t('page.stock.view')}}</a>
<!--              <Divider type="vertical" />-->
            </template>
          </vxe-column>
        </vxe-table>
        <div class="acea-row row-right page">
          <Page
              :total="total"
              :current="formValidate.page"
              @on-change="pageChange"
              :page-size="formValidate.limit"
          />
        </div>
      </div>
    </Card>
    <freightDetails :visible.sync="detailsVisible" :freight-id="freightId" @saved="getList"></freightDetails>
  </div>
</template>

<script>
import Setting from "@/setting";
import { mapState } from "vuex";
import freightDetails from '../components/freightDetails.vue';

import {freightHeaderInfo, freightList} from "@api/freight";
export default {
  name: "freightList",
  components: {
    freightDetails
  },
  data() {
    return {
      roterPre:Setting.roterPre,
	    props: { emitPath: false, multiple: true, checkStrictly: true },
      openErp:false,
      goodsId: "",
      data: [],
      headerList: [],
      total: 0,
      loading: false,
      stockNameList: [
        {
          value: '1791498718751334401',
          label: 'CA5005'
        },
        {
          value: '101816795504',
          label: 'Houston'
        }
      ],
      freightList: [],
      formValidate: {
        store_label_id: [],
        brand_id: [],
        store_name: "",
        cate_id: [],
        type: "0",
        page: 1,
        limit: 15,
      },
      freight_status:1,
      detailsVisible: false,
      freightId: 0,
      isAll: 0,
      isCheckBox: false,
      checkUidList:[],
      isLabel:0,
      brandData:[],
      storeLabelShow:false,
      storeDataLabel:[],
      timeVal:'',
    };
  },
  watch: {
    $route() {
      if (this.$route.fullPath === `${this.roterPre}/freight/index?type=5`) {
        this.getPath();
      }
    },
  },
  computed: {
    ...mapState("store/layout", ["isMobile"]),
    labelWidth() {
      return this.isMobile ? undefined : 80;
    },
    labelPosition() {
      return this.isMobile ? "top" : "right";
    },
	tabList() {
	    return this.headerList.map(item => ({
	      ...item,
	      name: this.$t(`page.freightTabs.${item.type}`)
	    }))
	  }
  },
  mounted() {
    this.getHeader();
  },
  methods: {
    // 具体日期
    onchangeTime(e) {
      this.timeVal = e;
      this.formValidate.archiving_period = this.timeVal;
    },
    formatTimeNative(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 标签弹窗关闭
    storeLabelClose() {
      this.storeLabelShow = false;
    },
    getLabelId(){
      let storeActiveIds = [];
      this.storeDataLabel.forEach((item)=>{
        storeActiveIds.push(item.id)
      });
      this.formValidate.store_label_id = storeActiveIds;
      this.search();
    },
    activeStoreData(storeDataLabel){
      this.storeLabelShow = false;
      this.storeDataLabel = storeDataLabel;
      this.getLabelId();
    },
    checkboxItem(e){
      let id = parseInt(e.rowid);
      let index = this.checkUidList.indexOf(id);
      if(index !== -1){
        this.checkUidList = this.checkUidList.filter((item)=> item !== id);
      }else{
        this.checkUidList.push(id);
      }
    },
    checkboxAll(){
      // 获取选中当前值
      let obj2 = this.$refs.xTable.getCheckboxRecords(true);
      // 获取之前选中值
      let obj = this.$refs.xTable.getCheckboxReserveRecords(true);
	  if(this.isAll == 0 && this.checkUidList.length <= obj.length && !this.isCheckBox){
	  	obj = [];
	  }
      obj = obj.concat(obj2);
      let ids = [];
      obj.forEach((item)=>{
        ids.push(parseInt(item.id))
      })
      this.checkUidList = ids;
      if(!obj2.length){
        this.isCheckBox = false;
      }
    },
    allPages(e){
      this.isAll = e;
      if(e==0){
        this.$refs.xTable.toggleAllCheckboxRow();
        // this.checkboxAll();
      }else{
        if(!this.isCheckBox){
          this.$refs.xTable.setAllCheckboxRow(true);
          this.isCheckBox = true;
          this.isAll = 1;
        }else{
          this.$refs.xTable.setAllCheckboxRow(false);
          this.isCheckBox = false;
          this.isAll = 0;
        }
        this.checkUidList = []
      }
    },
    allReset(){
      this.isAll = 0;
      this.isCheckBox = false;
      this.$refs.xTable.setAllCheckboxRow(false);
      this.checkUidList = [];
    },
    stockChange(stock) {
      this.freightList.forEach((item) => {
        if (this.goodsId == item.id) {
          item.branch_stock = stock;
        }
      });
    },
    //跳转刷新
    getPath() {
      this.formValidate.page = 1;
      this.formValidate.type = this.$route.query.type.toString();
      this.getList();
    },
    //获取列表
    getList() {
      this.loading = true;
      freightList(this.formValidate).then((res) => {
        this.freightList = res.data.list;
        this.total = res.data.count;
        this.loading = false;
        this.$nextTick(function(){
          if (this.isAll == 1) {
            if(this.isCheckBox){
              this.$refs.xTable.setAllCheckboxRow(true);
            }else{
              this.$refs.xTable.setAllCheckboxRow(false);
            }
          }else{
			let obj = this.$refs.xTable.getCheckboxReserveRecords(true);
			if(!this.checkUidList.length || this.checkUidList.length <= obj.length){
			  this.$refs.xTable.setAllCheckboxRow(false);
			}
          }
        })
      }).catch((err)=>{
        this.loading = false;
        this.$Message.error(err.msg);
      })
    },
    //头部列表
    getHeader() {
      this.loading = true;
      freightHeaderInfo(this.formValidate).then((res) => {
        this.headerList = res.data.list;
        if (this.$route.fullPath === `${Setting.roterPre}/freight/index?type=5`) {
          this.getPath();
        } else {
          this.getList();
        }
      });
    },
    //添加出库单
    add(){
      this.$refs.freight.modals = true;
    },
    //详情
    detail(id) {
      // this.goodsId = id;
      // this.isProductBox = true;
      this.detailsVisible = true;
      this.freightId = id;
    },
    // 编辑
    edit(row) {
      this.$router.push({ path: Setting.roterPre+"/freight/edit_freight/" + row.id });
    },
    //搜索
    search() {
      this.allReset();
      this.formValidate.page = 1;
      this.getHeader();
    },
    //重置
    reset() {
      this.formValidate.page = 1;
	    this.formValidate.store_label_id = [];
	    this.formValidate.brand_id = [];
      this.formValidate.store_name = "";
      this.formValidate.cate_id = [];
	    this.formValidate.type = "1";
	    this.storeDataLabel = [];
      this.getHeader();
    },
    //切换头部列表
    onClickTab(e) {
      this.allReset();
      this.formValidate.type = e;
      this.formValidate.page = 1;
	  this.getHeader();
      this.getList();
    },
    //分页
    pageChange(page) {
      this.formValidate.page = page;
      this.getList();
    },
  },
};
</script>

<style scoped lang="less">
/deep/.el-cascader {
	.el-input__inner {
	  min-height: 32px !important;
	}
	.el-input{
		.el-icon-arrow-down{
			font-size: 12px;
			color: #000;
		}
	}
	.el-cascader__search-input{
		margin-left: 7px !important;
		font-size: 12px;
	}
}
.labelInput{
  border: 1px solid #dcdee2;
  width :250px;
  padding: 0 5px;
  border-radius: 5px;
  min-height: 30px;
  cursor: pointer;
  .span{
    color: #c5c8ce;
	font-size: 12px;
  }
  .iconxiayi{
    font-size: 12px
  }
}
.labelClass{
  /deep/.ivu-form-item-content{
    line-height: unset;
  }
}
/deep/.ivu-form-label-left .ivu-form-item-label {
  text-align: right;
}

/deep/.ivu-page-header,
/deep/.ivu-tabs-bar {
  margin-bottom: 0px !important;
  border-bottom: 1px solid #E9E9E9;
}

/deep/.ivu-card-body {
  padding: 14px 20px 10px 20px !important;
}


/deep/.ivu-tabs-nav {
  height: 45px;
}

.bg {
  z-index: 100;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}

.tabbox {
  padding: 0px 20px 0px;
  // border-bottom: 1px solid #DCDFE6;
}

.box {
  padding: 20px;
  padding-bottom: 0px;
}

.tablebox {
  margin-top: 15px;
}

.btnbox {
  padding: 20px 0px 0px 30px;

  .btns {
    width: 99px;
    height: 32px;
    background: #1890ff;
    border-radius: 4px;
    text-align: center;
    line-height: 32px;
    color: #ffffff;
    cursor: pointer;
  }
}

.table {
  padding: 0px 30px 15px 30px;
}
.ivu-table {
  background-color: #182328;
  color: #fff;
}
.tabBox_img {
  width: 36px;
  height: 36px;
  border-radius: 4px;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }
}

.search {
  width: 86px;
  height: 32px;
  background: #1890ff;
  border-radius: 4px;
  text-align: center;
  line-height: 32px;
  font-size: 13px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #ffffff;
  cursor: pointer;
}

.reset {
  width: 86px;
  height: 32px;
  border-radius: 4px;
  border: 1px solid rgba(151, 151, 151, 0.36);
  text-align: center;
  line-height: 32px;
  font-size: 13px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  font-weight: 500;
  color: #515a6e;
  // background: #2D8CF0;

  cursor: pointer;
}
</style>